#### Figure S8: Distribution of violence support + difficulty parameter estimates ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

mirt_dat = data_pnas |> 
  select(violence1:violence6) |> 
  mutate(across(everything(), ~ 6-.x)) |> 
  mutate(across(everything(), ~ ifelse(is.na(.x), 0, .x)))

set.seed(123)
results_pcm = mirt::mirt(mirt_dat, itemtype = 'rsm', SE = T, verbose = F)
coef.pcm = mirt::coef(results_pcm, IRTpars = T, simplify = T)
mirt_dat$violence = mirt::fscores(results_pcm)[,1]
mirt_dat$weight = data_pnas$weight
mirt_dat$pid = data_pnas$pid

mirt_est = mirt_dat |> 
  filter(pid %in% c("Democrat","Republican")) |> 
  ggplot(aes(x = violence, fill = pid)) +
  geom_histogram(aes(y = ..density.. , weight = weight),
                 color= "black", position = 'identity',
                 binwidth = 1, alpha = .5) +
  scale_fill_manual(name = "Party",
                    values = c("blue","red")) +
  scale_y_continuous(labels = scales::percent) +
  labs(x = "Estimated Violence",
       y = NULL) +
  theme_prl()

mirt_diff = data.frame(
  diff = mirt::gen.difficulty(results_pcm),
  viol = c("Protest without\npermit", "Vandalism","Assault",
           "Arson","Assault with\ndeadly weapon", "Murder")
) |> 
  ggplot(aes(x = diff, y = reorder(viol,diff))) +
  geom_point() +
  geom_text(aes(x = diff + .5, label = round(diff,2)),
            size = 3) +
  theme_prl() +
  labs(x = "Item Difficulty Parameter", y = NULL)

fig_s8 = mirt_est + mirt_diff

print(fig_s8)

ggsave(here("Plots","Supplementary","figure_s8.png"),
       fig_s8,
       units = "in",
       width = 7, height = 4,
       dpi = 600)